package com.university.evaluation.controller;

import com.university.evaluation.entity.ScoreRecord;
import com.university.evaluation.service.MaterialAuditService;
import com.university.evaluation.mapper.ScoreRecordMapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

/**
 * 材料管理控制器
 * 实现需求文档中的材料提交和审核API
 */
@Slf4j
@RestController
@RequestMapping("/api/materials")
@RequiredArgsConstructor
@Tag(name = "材料管理", description = "材料提交、审核相关接口")
public class MaterialController {

    private final MaterialAuditService auditService;
    private final ScoreRecordMapper scoreRecordMapper;

    /**
     * 学生提交材料
     * POST /api/materials/submit
     */
    @PostMapping("/submit")
    @Operation(summary = "学生提交材料", description = "学生上传证明材料并提交审核")
    public ResponseEntity<ApiResponse<String>> submitMaterial(
            @RequestParam("file") MultipartFile file,
            @RequestParam("userId") String userId,
            @RequestParam("ruleId") String ruleId,
            @RequestParam("reason") String reason) {
        
        try {
            log.info("学生提交材料：userId={}, ruleId={}, reason={}", userId, ruleId, reason);
            
            // 1. 文件上传处理（简化实现，实际应使用文件存储服务）
            String fileName = file.getOriginalFilename();
            String materialPath = "/uploads/" + userId + "/" + System.currentTimeMillis() + "_" + fileName;
            String materialType = fileName.toLowerCase().endsWith(".pdf") ? "PDF" : "JPG";
            
            // TODO: 实际文件存储逻辑
            log.info("文件上传成功：materialPath={}", materialPath);
            
            // 2. 创建加分记录
            ScoreRecord record = new ScoreRecord();
            record.setRecordId(UUID.randomUUID().toString());
            record.setUserId(userId);
            record.setRuleId(ruleId);
            record.setMaterialPath(materialPath);
            record.setMaterialType(materialType);
            record.setReason(reason);
            record.setStatus(ScoreRecord.STATUS_PENDING_MON); // 初始状态：待班委审核
            record.setScore(BigDecimal.ZERO);
            record.setSubmitTime(LocalDateTime.now());
            record.setUpdateTime(LocalDateTime.now());
            
            scoreRecordMapper.insert(record);
            
            log.info("材料提交成功：recordId={}", record.getRecordId());
            return ResponseEntity.ok(new ApiResponse<>(true, "材料提交成功", record.getRecordId()));
            
        } catch (Exception e) {
            log.error("材料提交失败：userId={}, error={}", userId, e.getMessage(), e);
            return ResponseEntity.badRequest().body(new ApiResponse<>(false, "材料提交失败：" + e.getMessage(), null));
        }
    }

    /**
     * 班委审核材料
     * POST /api/materials/{materialId}/monitor-audit
     */
    @PostMapping("/{materialId}/monitor-audit")
    @Operation(summary = "班委审核材料", description = "班委对学生提交的材料进行初审")
    public ResponseEntity<ApiResponse<String>> monitorAudit(
            @PathVariable String materialId,
            @RequestParam String auditResult,
            @RequestParam String opinion,
            @RequestParam String auditorId) {
        
        try {
            log.info("班委审核材料：materialId={}, auditResult={}, auditorId={}", materialId, auditResult, auditorId);
            
            MaterialAuditService.AuditResult result = auditService.monitorAudit(materialId, auditResult, opinion, auditorId);
            
            if (result.isSuccess()) {
                return ResponseEntity.ok(new ApiResponse<>(true, result.getMessage(), materialId));
            } else {
                return ResponseEntity.badRequest().body(new ApiResponse<>(false, result.getMessage(), null));
            }
            
        } catch (Exception e) {
            log.error("班委审核失败：materialId={}, error={}", materialId, e.getMessage(), e);
            return ResponseEntity.badRequest().body(new ApiResponse<>(false, "审核失败：" + e.getMessage(), null));
        }
    }

    /**
     * 辅导员审核材料
     * POST /api/materials/{materialId}/teacher-audit
     */
    @PostMapping("/{materialId}/teacher-audit")
    @Operation(summary = "辅导员审核材料", description = "辅导员对材料进行终审并给分")
    public ResponseEntity<ApiResponse<String>> teacherAudit(
            @PathVariable String materialId,
            @RequestParam String auditResult,
            @RequestParam String opinion,
            @RequestParam String auditorId,
            @RequestParam(required = false) Double finalScore) {
        
        try {
            log.info("辅导员审核材料：materialId={}, auditResult={}, auditorId={}, finalScore={}", 
                    materialId, auditResult, auditorId, finalScore);
            
            MaterialAuditService.AuditResult result = auditService.teacherAudit(materialId, auditResult, opinion, auditorId, finalScore);
            
            if (result.isSuccess()) {
                return ResponseEntity.ok(new ApiResponse<>(true, result.getMessage(), materialId));
            } else {
                return ResponseEntity.badRequest().body(new ApiResponse<>(false, result.getMessage(), null));
            }
            
        } catch (Exception e) {
            log.error("辅导员审核失败：materialId={}, error={}", materialId, e.getMessage(), e);
            return ResponseEntity.badRequest().body(new ApiResponse<>(false, "审核失败：" + e.getMessage(), null));
        }
    }

    /**
     * 查询我的材料记录
     * GET /api/materials/my-records
     */
    @GetMapping("/my-records")
    @Operation(summary = "查询我的材料记录", description = "学生查询自己提交的材料记录")
    public ResponseEntity<ApiResponse<List<ScoreRecord>>> getMyRecords(@RequestParam String userId) {
        try {
            List<ScoreRecord> records = scoreRecordMapper.findByUserId(userId);
            return ResponseEntity.ok(new ApiResponse<>(true, "查询成功", records));
        } catch (Exception e) {
            log.error("查询材料记录失败：userId={}, error={}", userId, e.getMessage(), e);
            return ResponseEntity.badRequest().body(new ApiResponse<>(false, "查询失败：" + e.getMessage(), null));
        }
    }

    /**
     * 查询待审核材料（班委用）
     * GET /api/materials/pending-monitor
     */
    @GetMapping("/pending-monitor")
    @Operation(summary = "查询待班委审核材料", description = "班委查询待审核的材料列表")
    public ResponseEntity<ApiResponse<List<ScoreRecord>>> getPendingMonitorRecords(@RequestParam String collegeId) {
        try {
            List<ScoreRecord> records = scoreRecordMapper.findPendingMonitorRecordsByCollege(collegeId);
            return ResponseEntity.ok(new ApiResponse<>(true, "查询成功", records));
        } catch (Exception e) {
            log.error("查询待班委审核材料失败：collegeId={}, error={}", collegeId, e.getMessage(), e);
            return ResponseEntity.badRequest().body(new ApiResponse<>(false, "查询失败：" + e.getMessage(), null));
        }
    }

    /**
     * 查询待审核材料（辅导员用）
     * GET /api/materials/pending-teacher
     */
    @GetMapping("/pending-teacher")
    @Operation(summary = "查询待辅导员审核材料", description = "辅导员查询待审核的材料列表")
    public ResponseEntity<ApiResponse<List<ScoreRecord>>> getPendingTeacherRecords(@RequestParam String collegeId) {
        try {
            List<ScoreRecord> records = scoreRecordMapper.findPendingTeacherRecordsByCollege(collegeId);
            return ResponseEntity.ok(new ApiResponse<>(true, "查询成功", records));
        } catch (Exception e) {
            log.error("查询待辅导员审核材料失败：collegeId={}, error={}", collegeId, e.getMessage(), e);
            return ResponseEntity.badRequest().body(new ApiResponse<>(false, "查询失败：" + e.getMessage(), null));
        }
    }

    /**
     * 通用API响应类
     */
    public static class ApiResponse<T> {
        private boolean success;
        private String message;
        private T data;

        public ApiResponse(boolean success, String message, T data) {
            this.success = success;
            this.message = message;
            this.data = data;
        }

        // Getters
        public boolean isSuccess() { return success; }
        public String getMessage() { return message; }
        public T getData() { return data; }
    }
}
